package com.jiyinit.web.core.business.controller;

import com.jiyinit.core.framework.base.entity.ResponseDto;
import com.jiyinit.core.framework.base.paging.PagingResult;
import com.jiyinit.core.framework.base.util.Check;
import com.jiyinit.core.framework.base.util.JsonEntityTransform;
import com.jiyinit.core.framework.base.util.LogUtil;
import com.jiyinit.web.core.business.dto.RolePageRequest;
import com.jiyinit.web.core.business.entity.TabCoreRoleEntity;
import com.jiyinit.web.core.business.entity.TabCoreRoleResourceEntity;
import com.jiyinit.web.core.business.enums.ResourceTypeEnum;
import com.jiyinit.web.core.business.service.ResourceServiceImpl;
import com.jiyinit.web.core.business.service.RoleResourceServiceImpl;
import com.jiyinit.web.core.business.service.RoleServiceImpl;
import com.jiyinit.web.core.business.vo.RoleResourceVo;
import com.jiyinit.web.core.common.logic.ParamCheckLogic;
import com.jiyinit.web.core.common.util.UserUtil;
import com.jiyinit.web.core.common.vo.CurrentUserVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * <p></p>
 * <p>
 * <PRE>
 * <BR>	修改记录
 * <BR>-----------------------------------------------
 * <BR>	修改日期			修改人			修改内容
 * </PRE>
 *
 * @author lishaochuan
 * @version 1.0
 * @date 2017/4/19 17:34
 * @since 1.0
 */
@Controller
@RequestMapping("/role")
public class RoleController {

    /**
     * 日志对象
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(ResourceController.class);

    @Resource(name = "core.paramCheckLogic")
    private ParamCheckLogic paramCheckLogic;

    @Resource(name = "core.roleServiceImpl")
    RoleServiceImpl roleService;

    @Resource(name = "core.resourceServiceImpl")
    ResourceServiceImpl resourceService;

    @Resource(name = "core.roleResourceServiceImpl")
    RoleResourceServiceImpl roleResourceService;


    /**
     * 角色管理页面
     * @author lishaochuan
     * @create 2017/4/19 17:37
     * @param
     * @return
     */
    @RequestMapping("/roleList")
    public String roleList() {
        return "/role/roleList";
    }

    /**
     * 分页查询角色
     * @author lishaochuan
     * @create 2017/4/19 17:35
     * @param
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/getRoleForPage")
    @ResponseBody
    public PagingResult getRoleForPage(RolePageRequest rolePageRequest){
        PagingResult<TabCoreRoleEntity> pagingResult = roleService.selectRoleForPage(rolePageRequest);
        LogUtil.info(LOGGER,"pagingResult:{}", JsonEntityTransform.object2Json(pagingResult));
        return pagingResult;
    }

    /**
     * 角色添加页面
     * @author lishaochuan
     * @create 2017/4/20 10:44
     * @param
     * @return
     */
    @RequestMapping(value = "/toRoleAdd")
    public String toRoleAdd(HttpServletRequest request, Integer parentId) {
        return "/role/roleAdd";
    }


    /**
     * 保存角色
     * @author lishaochuan
     * @create 2017/4/20 11:05
     * @param
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/roleAdd")
    @ResponseBody
    public ResponseEntity<ResponseDto> roleAdd(TabCoreRoleEntity tabCoreRoleEntity){
        if(Check.isNullObj(tabCoreRoleEntity) || Check.isNullStr(tabCoreRoleEntity.getRoleName())){
            return new ResponseEntity<>(ResponseDto.responseFail("角色名称不能为空"), HttpStatus.OK);
        }
        CurrentUserVo currentUser = UserUtil.getCurrentUser();
        Integer userId = currentUser.getUserId();
        tabCoreRoleEntity.setCreateId(userId);
        tabCoreRoleEntity.setCreateTime(new Date());

        int num = roleService.save(tabCoreRoleEntity);
        if(num == 1){
            return new ResponseEntity<>(ResponseDto.responseOK(""), HttpStatus.OK);
        }
        return new ResponseEntity<>(ResponseDto.responseFail("系统错误"), HttpStatus.OK);
    }


    /**
     * 修改角色页面
     * @author lishaochuan
     * @create 2017/4/20 11:34
     * @param
     * @return
     */
    @RequestMapping(value = "/toRoleUpdate")
    public String toTreeUpdate(HttpServletRequest request, Integer roleId) {
        TabCoreRoleEntity coreRole = roleService.selectRoleById(roleId);
        request.setAttribute("role", coreRole);
        return "/role/roleUpdate";
    }

    /**
     * 修改角色
     * @author lishaochuan
     * @create 2017/4/20 11:45
     * @param
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/roleUpdate")
    @ResponseBody
    public ResponseEntity<ResponseDto> roleUpdate(TabCoreRoleEntity tabCoreRoleEntity){
        if(Check.isNullObj(tabCoreRoleEntity) || Check.isNullObjs(tabCoreRoleEntity.getRoleId(), tabCoreRoleEntity.getRoleName())){
            return new ResponseEntity<>(ResponseDto.responseFail("参数错误"), HttpStatus.OK);
        }
        CurrentUserVo currentUser = UserUtil.getCurrentUser();
        Integer userId = currentUser.getUserId();
        tabCoreRoleEntity.setLastModifyId(userId);
        tabCoreRoleEntity.setLastModifyTime(new Date());

        int num = roleService.update(tabCoreRoleEntity);
        if(num == 1){
            return new ResponseEntity<>(ResponseDto.responseOK(""), HttpStatus.OK);
        }
        return new ResponseEntity<>(ResponseDto.responseFail("系统错误"), HttpStatus.OK);
    }


    /**
     * 删除角色
     * @author lishaochuan
     * @create 2017/4/20 12:00
     * @param
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/roleDelete")
    @ResponseBody
    public ResponseEntity<ResponseDto> roleDelete(Integer[] roleIds) {
        int num = roleService.deleteByRoleIds(roleIds);
        if (num > 0) {
            return new ResponseEntity<>(ResponseDto.responseOK(""), HttpStatus.OK);
        }
        return new ResponseEntity<>(ResponseDto.responseFail("系统错误"), HttpStatus.OK);
    }

    /**
     * 分配权限页面
     * @author lishaochuan
     * @create 2017/4/20 18:12
     * @param
     * @return
     */
    @RequestMapping(value = "/toRoleTreeUpdate")
    public String toRoleTreeUpdate(HttpServletRequest request, Integer roleId) {
        request.setAttribute("roleId", roleId);
        return "/role/roleTreeUpdate";
    }


    /**
     * 查询角色权限
     * @author lishaochuan
     * @create 2017/4/20 18:17
     * @param
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/findRoleResource")
    @ResponseBody
    public ResponseEntity<ResponseDto> findRoleResource(Integer roleId) {
        List<RoleResourceVo> roleResources = resourceService.findResourceByRoleId(roleId);
        List items = new ArrayList<>();
        for (RoleResourceVo roleResourceVo : roleResources) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", roleResourceVo.getResourceId());
            map.put("pId", roleResourceVo.getParentId());
            map.put("name", roleResourceVo.getResourceName());
            if(ResourceTypeEnum.FUNCTION.getCode().equals(roleResourceVo.getResourceType())){
                map.put("open", false);
            } else {
                map.put("open", true);
            }
            if(!Check.isNullObj(roleResourceVo.getRoleId())){
                map.put("checked", true);
            }
            items.add(map);
        }
        return new ResponseEntity<>(ResponseDto.responseOK(items), HttpStatus.OK);
    }


    /**
     * 修改角色权限
     * @author lishaochuan
     * @create 2017/4/21 15:54
     * @param
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/updateRoleResource")
    @ResponseBody
    public ResponseEntity<ResponseDto> updateRoleResource(Integer roleId, Integer[] resourceIds) {
        if(Check.isNullObj(roleId)){
            return new ResponseEntity<>(ResponseDto.responseFail("参数错误"), HttpStatus.OK);
        }
        CurrentUserVo currentUser = UserUtil.getCurrentUser();
        Integer userId = currentUser.getUserId();
        Date date = new Date();
        List<TabCoreRoleResourceEntity> roleResources = new ArrayList<>();
        for (Integer resourceId : resourceIds) {
            TabCoreRoleResourceEntity roleResourceEntity = new TabCoreRoleResourceEntity();
            roleResourceEntity.setRoleId(roleId);
            roleResourceEntity.setResourceId(resourceId);
            roleResourceEntity.setCreateId(userId);
            roleResourceEntity.setCreateTime(date);
            roleResourceEntity.setLastModifyId(userId);
            roleResourceEntity.setLastModifyTime(date);
            roleResources.add(roleResourceEntity);
        }
        roleResourceService.updateRoleResource(roleId, roleResources);
        return new ResponseEntity<>(ResponseDto.responseOK(""), HttpStatus.OK);
    }



    @RequestMapping("/toRoleTree")
    public String toRoleTree(HttpServletRequest request) {
        return "/role/roleTree";
    }

    @ResponseBody
    @RequestMapping("/getRoleTree")
    public ResponseEntity<ResponseDto> getOrgTree(HttpServletRequest request) {
        List items = this.fillTree();
        return new ResponseEntity<>(ResponseDto.responseOK(items), HttpStatus.OK);
    }

    private List fillTree(){
        List<TabCoreRoleEntity> roleList = roleService.selectAll();
        List items = new ArrayList<>();
        for (TabCoreRoleEntity role : roleList) {
            Map map = new HashMap();
            map.put("id", role.getRoleId());
            map.put("pId", 0);
            map.put("name", role.getRoleName());
            map.put("isParent", false);
            items.add(map);
        }
        return items;
    }

    @RequestMapping("/toRoleChoose")
    public String toRoleChoose(HttpServletRequest request) {
        return "/role/roleChoose";
    }
}
